import { Component, ViewEncapsulation } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { deepClone } from '../../../utils/utils';

@Component({
  selector: 'apes-render-showHidden',
  template: `
    <div class="render-showHidden">
      {{showHidden(params.value)}}
    </div>
  `,
  styles: [
      `
      .render-showHidden {
        white-space: pre-wrap;
      }
    `,
  ],
})
export class RenderShowHiddenComponent implements ICellRendererAngularComp {
  params: any;
  apesConfig: any;


  ctx: any = {};
  data: any = {};
  colKey: any = '';
  valueFormatter = '';

  constructor(
    private  expressionService: ExpressionService,
  ) {
  }

  refresh(params: any): boolean {
    return false;
  }

  agInit(params): void {
    this.params = params;
    this.ctx = params.context;
    this.apesConfig = this.extend(params);

    if (params.context) {
      this.ctx = params.context;
    }

    if (this.params.hasOwnProperty('colDef')) {
      this.data = this.params.data;
      this.colKey = this.params.colDef.field;
      this.valueFormatter = deepClone(params.colDef['valueFormatter']);
    } else {
      this.data = this.params.node.data;
      this.colKey = this.params['column']['colDef'].field;
      this.valueFormatter = deepClone(params.column['colDef']['valueFormatter']);
    }
  }

  extend(data: any) {
    let result = {};
    for (let key in data) {
      let value = data[key];
      if (key === 'context') {
        result['ctx'] = value;
      } else {
        result[key] = value;
      }
    }
    return result;
  }

  showHidden(value) {
    let show;
    let showHidden = this.params.column['colDef'].showHidden;
    let hiddenRegExp = this.params.column['colDef'].hiddenRegExp;
    // console.log('showHidden',showHidden);
    if (showHidden) {
      show = this.formatter(value, this.valueFormatter || 'value');
    } else {
      if (hiddenRegExp) {
        let regExpValue = this.formatter(value, this.valueFormatter || 'value');
        // tslint:disable-next-line:no-eval
        hiddenRegExp = eval(hiddenRegExp);
        let replaceValue = this.params.column['colDef'].replaceValue;
        // show = regExpValue.replace(/^\[(.{3})(?:\w+)(.{3})\](.*)$/, '\[\$1****\$2\]\$3');
        show = regExpValue.replace(hiddenRegExp, replaceValue);
      } else {
        show = '****';
      }
    }
    return show;
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: '',
      model: '',
      data: this.data,
      value: value,
    });
  }

}
